package com.mindfreez.shipping.usps;

import com.mindfreez.shipping.Address;
import com.mindfreez.shipping.usps.domain.AddressValidationRequest;
import com.thoughtworks.xstream.XStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

public class AddressService {
    private static final Logger log = Logger.getLogger(AddressService.class);
    private String server;
    private String userId;

    public AddressService(String server, String userId) {
        this.server = server;
        this.userId = userId;
    }
    
    public Address verify(Address address) {
        XStream xStream = new XStream();
        xStream.processAnnotations(new Class[] {AddressValidationRequest.class, com.mindfreez.shipping.usps.domain.Address.class});
        
        com.mindfreez.shipping.usps.domain.Address uspsAddress = new com.mindfreez.shipping.usps.domain.Address();
        uspsAddress.setId("1");
        uspsAddress.setAddress2(address.getStreet());
        uspsAddress.setCity(address.getCity());
        uspsAddress.setState(address.getState());
        uspsAddress.setZip5(address.getPostalCode());
        
        AddressValidationRequest request = new AddressValidationRequest();
        request.setUserId(userId);
        request.setAddress(uspsAddress);
        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("API", "VERIFY"));
        params.add(new BasicNameValuePair("XML", xStream.toXML(request)));
        
        
        try {
//            URI uri = URIUtils.createURI("http", "testing.shippingapis.com", -1, "/ShippingAPITest.dll", URLEncodedUtils.format(params, "UTF-8"), null);
            URI uri = URIUtils.createURI("http", "production.shippingapis.com", -1, "/ShippingAPI.dll", URLEncodedUtils.format(params, "UTF-8"), null);

            HttpClient httpclient = new DefaultHttpClient();

            HttpGet get = new HttpGet(uri);

            log.debug(get.getURI());
            
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = httpclient.execute(get, responseHandler);
            
            log.debug(response);
        } catch (IOException ex) {
            log.error(ex);
        } catch (URISyntaxException ex) {
            log.error(ex);
        }
        
        return address;
    }
}
